package com.yuting.gateway.filter;

import com.yuting.gateway.rpc.RpcUserService;
import com.yuting.gateway.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.UUID;

@Component
@Slf4j
public class UserAuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private RpcUserService rpcUserService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();

        HttpCookie cookie = cookies.getFirst("token");

        String path = request.getURI().getPath();
        if(cookie == null){
//            if(CommonUtil.isLogin(path)){
//                ResponseCookie tokenCookie = ResponseCookie.from("token",UUID.randomUUID().toString()).httpOnly(false).path("/").build();
//                response.addCookie(tokenCookie);
//                return chain.filter(exchange);
//            }

            if(CommonUtil.needToken(path)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String data = "please login first";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }

        }else{
            log.info("token-{}", cookie.getValue());
            // 有token的情况下，
            String userInfo = rpcUserService.userInfo(cookie.getValue());
            if(userInfo.equals("error")){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String data = "token error";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
